import './polyfill';
import dva from 'dva';
import fetch from 'dva/fetch';
import {notification} from 'antd';

import createHistory from 'history/createHashHistory';
import createLoading from 'dva-loading';
import {baseServerUrl, unAuthUrl, token} from './utils/Constant';

import './index.less';
import {getAuthority} from "./utils/authority";

const t = getAuthority() ? getAuthority() : token;

export default fetch(`${ baseServerUrl }/tms/auth/menu-list`, {
  method: 'GET',
  credentials: 'include',
  headers: {token: t},
})
  .then(res => {
    if (res.status === 401) {
      window.location.href = unAuthUrl;
      throw new Error("系统未授权，请重新登陆！")
    }
    return res.json();
  })
  .then(json => {
    // 1. Initialize
    const app = dva({
      history: createHistory(),
      initialState: {
        global: {
          // menuData: json,
          // defaultRedirect: 'base-info/customer'
          menuData: json.result.menuList,
          defaultRedirect: json.result.defaultRedirect,
        },
      },
    });
    // 2. Plugins
    app.use(createLoading());

    // 3. Register global model
    app.model(require('./models/global').default);

    // 4. Router
    app.router(require('./router').default);

    // 5. Start
    app.start('#root');
    return app._store;
  })
  .catch(e => {
    notification.error({
      message: '初始化系统失败！',
    });
    throw e;
  });
